import { reactive } from "vue";
import router from "../router/index";
import axios from "axios";
import { Toast } from "vant";
/**
 * 注册请求接口
 */
export const RequestReq = () => {
  const user = reactive({
    username: "lihua",
    password: "123",
    age: "45",
    nickname: "gbc",
    fullname: "nfh",
    sex: "nv",
  });
  const backStart = () => {
    history.back();
  };
  const onRegister = async () => {
    const { username, password, nickname, age, sex, fullname } =
      user;
    let res = await axios({
      method: "post",
      url: "/api/users/UserRegister",
      data: {
        username,
        password,
        nickname,
        age,
        fullname,
        sex,
      },
    });
      console.log(res);
      
    if (res.data.Code == 1) {
      Toast({
        message: "注册成功",
        position: "top",
      });

      router.push({ path: "/login" });
    } else {
      Toast({
        message: "注册失败",
        position: "top",
      });
      console.log("注册失败");
      return false;
    }
  };
  return {
    user,
    onRegister,
    backStart,
  };
};

/**
 * 登录请求接口
 */
export const LoginReq = () => {
  const user = reactive({
    username: "xm001",
    password: "user123",
  });
  const backStart = () => {
    history.back();
  };
  const onLogin = () => {
    const { username, password } = user;
    axios({
      method: "post",
      url: "/api/users/UserLogin",
      data: {
        username,
        password,
      },
    })
      .then((data) => {
        console.log(data.data.info);
        if (data.data.Code == 1) {
          Toast({
            message: "登录成功",
            position: "top",
          });
          //信息存入session域
          sessionStorage.setItem('userInfo',JSON.stringify(data.data.info))
          router.push({ path: "/home/index" })
        }else{
          Toast({
            message: "失败",
            position: "top",
          });
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };
  return { user, onLogin, backStart };
};
